package com.hyphenate.easeui.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.ClipboardManager;
import android.text.format.Time;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.chatuidemo.DemoApplication;
import com.hyphenate.chatuidemo.DemoHelper;

import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseAlertDialog.AlertDialogUser;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu.ChatInputMenuListener;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView.EaseVoiceRecorderCallback;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.util.EMLog;
import com.joplus.housekeeper.R;
import com.joplus.housekeeper.bean.ChatCard;
import com.joplus.housekeeper.bean.ChatResultBean;
import com.joplus.housekeeper.bean.MessageAccountListBean;
import com.joplus.housekeeper.bean.MessageRecordListBean;
import com.joplus.housekeeper.bean.RecordListBean;
import com.joplus.housekeeper.core.Config;
import com.joplus.housekeeper.network.RequestHelper;
import com.joplus.housekeeper.network.TextCallback;

import com.joplus.housekeeper.utils.BitmapUtil;
import com.joplus.housekeeper.utils.Imageutils;
import com.joplus.housekeeper.utils.L;
import com.joplus.housekeeper.utils.RealmHelper;
import com.joplus.housekeeper.utils.SPUtils;
import com.joplus.housekeeper.utils.StringUtils;
import com.joplus.housekeeper.utils.T;
import com.joplus.housekeeper.utils.UMengUtils;
import com.joplus.housekeeper.utils.WorkTimeUtil;
import com.joplus.housekeeper.xmpp.SmackManager;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.realm.RealmResults;

/**
 * 可以直接new出来使用的聊天对话页面fragment，
 * 使用时需调用setArguments方法传入chatType(会话类型)和userId(用户或群id)
 * app也可继承此fragment续写
 * <br/>
 * <br/>
 * 参数传入示例可查看demo里的ChatActivity
 */
public class EaseChatFragment extends EaseBaseFragment {

    protected static final String TAG = "EaseChatFragment";
    protected static final int REQUEST_CODE_MAP = 1;
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;
    /**
     * 传入fragment的参数
     */
    protected Bundle fragmentArgs;
    protected int chatType;
    protected String toChatUsername;
    protected EaseChatMessageList messageList;
    protected EaseChatInputMenu inputMenu;

    protected EMConversation conversation;
    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;
    //   protected Handler handler = new Handler();
    protected File cameraFile;
    protected EaseVoiceRecorderView voiceRecorderView;
    //    protected SwipeRefreshLayout ;
    private PtrClassicFrameLayout mPtrFrame;
    protected ListView listView;
    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected EMGroupChangeListener groupListener;
    protected EMMessage contextMenuMessage;
    static final int TIEM_EXPRESSION = 4;//表情
    static final int ITEM_TAKE_PICTURE = 1;
    static final int ITEM_PICTURE = 2;
    static final int ITEM_LOCATION = 3;


   /* protected int[] itemStrings = {R.string.attach_smile, R.string.attach_take_pic, R.string.attach_picture, R.string.attach_location};
    protected int[] itemdrawables = {R.drawable.chatfaceicon, R.drawable.jo_chat_takepic, R.drawable.jo_chat_image,
            R.drawable.ease_chat_location_selector};
    protected int[] itemIds = {TIEM_EXPRESSION, ITEM_TAKE_PICTURE, ITEM_PICTURE, ITEM_LOCATION};*/

    protected int[] itemStrings = {R.string.attach_take_pic, R.string.attach_picture, R.string.attach_location};
    protected int[] itemdrawables = {R.drawable.jo_chat_takepic, R.drawable.jo_chat_image,
            R.drawable.ease_chat_location_selector};
    protected int[] itemIds = {ITEM_TAKE_PICTURE, ITEM_PICTURE, ITEM_LOCATION};
    private EMChatRoomChangeListener chatRoomChangeListener;
    private boolean isMessageListInited;
    protected MyItemClickListener extendMenuItemClickListener;


    public ViewPager vp;

    private String localareaId;

    private EMMessage message;
    private int size;
    private String serviceName;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.ease_fragment_chat, container, false);
    }

    public MessageAccountListBean user;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        fragmentArgs = getArguments();
        // 判断单聊还是群聊
        //   chatType = fragmentArgs.getInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        chatType = EaseConstant.CHATTYPE_SINGLE;
        // 会话人或群组id

        user = fragmentArgs.getParcelable("user");

        toChatUsername = user.getAccountId();
        serviceName = (String) SPUtils.get(getContext(), "im", " ");
        if (savedInstanceState != null) {
            cameraFile = new File(savedInstanceState.getString("tempFile", ""));
        }

        requestMessage();
        super.onActivityCreated(savedInstanceState);
        inputMenu.setRightClick(new EaseChatInputMenu.RightClick() {
            @Override
            public void camera() {
                selectPicFromCamera();
            }
        });
    }

    /**
     * init view
     */
    public void initView() {
        // 按住说话录音控件
        voiceRecorderView = (EaseVoiceRecorderView) getView().findViewById(R.id.voice_recorder);
        // 消息列表layout
        messageList = (EaseChatMessageList) getView().findViewById(R.id.message_list);
        if (chatType != EaseConstant.CHATTYPE_SINGLE)
            messageList.setShowUserNick(true);
        listView = messageList.getListView();

        extendMenuItemClickListener = new MyItemClickListener();
        inputMenu = (EaseChatInputMenu) getView().findViewById(R.id.input_menu);


        registerExtendMenuItem();
        // init input menu
        inputMenu.init(null);

        inputMenu.setChatInputMenuListener(new ChatInputMenuListener() {
            @Override
            public void onSendMessage(String content) throws UnsupportedEncodingException {
                // 发送文本消息
                sendTextMessage(content);
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderCallback() {
                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {

                        sendVoiceMessage(voiceFilePath, voiceTimeLength);

                        MessageRecordListBean messageRecordListBean = new MessageRecordListBean();
                        messageRecordListBean.setType(2);
                        messageRecordListBean.setContent((getString(voiceFilePath)));
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        messageRecordListBean.setMessageDatetime(System.currentTimeMillis());
                        messageRecordListBean.setMessageId(uuid);
                        messageRecordListBean.setClientType(0);
                        messageRecordListBean.setDuration(voiceTimeLength);
                        messageRecordListBean.setAccountId(user.getAccountId());
                        messageRecordListBean.setMobile(user.getMobile());
                        messageRecordListBean.setMessageFrom(serviceName);
                        messageRecordListBean.setMessageTo(user.getImId());
                        String s1 = new Gson().toJson(messageRecordListBean);
                        messageRecordListBean.setContent(voiceFilePath);
                        mySend(s1, user.getImId(), messageRecordListBean);
                    }
                });
            }

            @Override
            public void onGifClick(String iconCode) {
                try {
                    ChatCard chatCard = new ChatCard();
                    chatCard.setSubject("gif");
                    chatCard.setMessage(iconCode);
                    Gson gson = new Gson();
                    String s1 = gson.toJson(chatCard);

                    MessageRecordListBean messageRecordListBean = new MessageRecordListBean();
                    messageRecordListBean.setType(8);
                    messageRecordListBean.setContent(Base64.encodeToString(iconCode.getBytes("UTF-8"), Base64.DEFAULT));
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    messageRecordListBean.setMessageDatetime(System.currentTimeMillis());
                    messageRecordListBean.setMessageId(uuid);
                    messageRecordListBean.setClientType(0);
                    messageRecordListBean.setAccountId(user.getAccountId());
                    messageRecordListBean.setMobile(user.getMobile());
                    messageRecordListBean.setMessageFrom(serviceName);
                    messageRecordListBean.setMessageTo(user.getImId());
                    String s2 = new Gson().toJson(messageRecordListBean);
                    messageRecordListBean.setContent(s1);
                    mySend(s2, user.getImId(), messageRecordListBean);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
                //发送大表情(动态表情)
                sendBigExpressionMessage(emojicon.getName(), emojicon.getIdentityCode());
            }
        });

        mPtrFrame = messageList.getPtrFrame();

        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setLoadingMinTime(1000);

        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                frame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPtrFrame.refreshComplete();
                        requestMessage();
                        messageList.refreshSeekTo(size - 1);
                    }
                }, 600);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });


        inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    }


    private String getString(String path) {
        File file = new File(path);
        byte[] buffer = new byte[(int) file.length()];
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);


            inputFile.read(buffer);
            inputFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return Base64.encodeToString(buffer, Base64.DEFAULT);

    }


    public void sendTextMessagetToFrontAndServer(String frontMsg, String serMsg) {

//        //本地的消息
        EMMessage messages = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
//        messages.setFrom(DemoHelper.getInstance().getCurrentUsernName());
//        messages.setReceipt(Config.CUSTOM_SERVICE_IMID);
        messages.setFrom(Config.CUSTOM_SERVICE_IMID);
        messages.setTo(DemoHelper.getInstance().getCurrentUsernName());
        messages.addBody(new EMTextMessageBody(frontMsg));
        messages.setMsgTime(System.currentTimeMillis());
        messages.setStatus(EMMessage.Status.SUCCESS);
        messages.setDirection(EMMessage.Direct.RECEIVE);
        conversation.appendMessage(messages);

        //发送给服务器的消息
        EMMessage serMessage = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
        serMessage.setFrom(DemoHelper.getInstance().getCurrentUsernName());
        serMessage.setTo(Config.CUSTOM_SERVICE_IMID);
        serMessage.addBody(new EMTextMessageBody(serMsg));
        serMessage.setMsgTime(System.currentTimeMillis());
        serMessage.setStatus(EMMessage.Status.SUCCESS);
        serMessage.setDirection(EMMessage.Direct.SEND);
        //sendMessage(serMessage);
        sendTextMessageToService(serMsg);
    }

    //发送给后台客服
    public void sendTextMessageToService(String content) {
        final EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        message.setDirection(EMMessage.Direct.SEND);
        sendMessage(message);

        message.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                conversation.removeMessage(message.getMsgId());
                messageList.refresh();

            }

            @Override
            public void onError(int i, String s) {
                conversation.removeMessage(message.getMsgId());
                messageList.refresh();
            }

            @Override
            public void onProgress(int i, String s) {
                conversation.removeMessage(message.getMsgId());
                messageList.refresh();
            }
        });
    }

    public void insertMessage(String sendText) {
        if (!StringUtils.isEmpty(sendText)) {
            EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            message.setFrom(Config.CUSTOM_SERVICE_IMID);
            message.setTo(DemoHelper.getInstance().getCurrentUsernName());
            message.addBody(new EMTextMessageBody(sendText));
            message.setChatType(EMMessage.ChatType.Chat);
            message.setTo(DemoHelper.getInstance().getCurrentUsernName());
            message.setMsgTime(System.currentTimeMillis());
            // conversation.insertMessage(message);
            conversation.appendMessage(message);

            messageList.refresh();
        }

    }




    public void insertMessageToDb(String sendText) {
        if (!StringUtils.isEmpty(sendText)) {
            EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            message.setFrom(Config.CUSTOM_SERVICE_IMID);
            //  message.setTo(DemoApplication.getInstance().getUser().getData().getMobile());
            message.addBody(new EMTextMessageBody(sendText));
            message.setChatType(EMMessage.ChatType.Chat);
            message.setMsgId(UUID.randomUUID().toString());

            //  conversation.insertMessage(message);

            //  conversation.appendMessage(message);

            EMClient.getInstance().chatManager().saveMessage(message);
           /* EaseNotifier notifier = EaseUI.getInstance().getNotifier();
            notifier.onNewMsg(message);
*/
            messageList.refresh();
        }

    }

    public void insertVoice(String filePaht, int length, String toChatUsername) {
        EMMessage voiceSendMessage = createReceiveMessage(filePaht, length, toChatUsername);
        voiceSendMessage.setChatType(EMMessage.ChatType.Chat);
        voiceSendMessage.setFrom(Config.CUSTOM_SERVICE_IMID);
        voiceSendMessage.setTo(toChatUsername);
        voiceSendMessage.setMsgTime(System.currentTimeMillis());
        conversation.appendMessage(voiceSendMessage);
        messageList.refresh();
    }

    public EMMessage createReceiveMessage(String filePath, int length, String toChatUsername) {
        EMMessage receiveMessage = EMMessage.createReceiveMessage(EMMessage.Type.VOICE);
        EMVoiceMessageBody emVoiceMessageBody = new EMVoiceMessageBody(new File(filePath), length);
        receiveMessage.addBody(emVoiceMessageBody);
        receiveMessage.setTo(toChatUsername);
        receiveMessage.setChatType(EMMessage.ChatType.Chat);
        receiveMessage.setFrom(Config.CUSTOM_SERVICE_IMID);
        receiveMessage.setMsgTime(System.currentTimeMillis());
        return receiveMessage;
    }

    public void insertPic(Bitmap bitmap) {

        EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.IMAGE);
        message.setFrom(Config.CUSTOM_SERVICE_IMID);
        message.setTo(DemoHelper.getInstance().getCurrentUsernName());

        message.addBody(new EMImageMessageBody(Imageutils.savePic(bitmap)));
        message.setChatType(EMMessage.ChatType.Chat);
        message.setTo(DemoHelper.getInstance().getCurrentUsernName());
        message.setMsgTime(System.currentTimeMillis());
        // conversation.insertMessage(message);
        conversation.appendMessage(message);

        L.e("from :" + Config.CUSTOM_SERVICE_IMID + " to :" + DemoHelper.getInstance().getCurrentUsernName());
        messageList.refresh();


    }

    public void sendPicMessagetToFront(File file) {

//        //本地的消息
        EMMessage messages = EMMessage.createReceiveMessage(EMMessage.Type.IMAGE);
//        messages.setFrom(DemoHelper.getInstance().getCurrentUsernName());
//        messages.setReceipt(Config.CUSTOM_SERVICE_IMID);
        messages.setFrom(Config.CUSTOM_SERVICE_IMID);
        messages.setTo(DemoHelper.getInstance().getCurrentUsernName());
        messages.addBody(new EMImageMessageBody(file));
        messages.setMsgTime(System.currentTimeMillis());
        messages.setStatus(EMMessage.Status.SUCCESS);
        messages.setDirection(EMMessage.Direct.RECEIVE);
        conversation.appendMessage(messages);


    }

    public void insertPic(File file) {
        EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.IMAGE);
        message.setFrom(Config.CUSTOM_SERVICE_IMID);
        message.setTo(DemoHelper.getInstance().getCurrentUsernName());

        message.addBody(new EMImageMessageBody(file));
        message.setChatType(EMMessage.ChatType.Chat);
        message.setTo(DemoHelper.getInstance().getCurrentUsernName());
        message.setMsgTime(System.currentTimeMillis());
        // conversation.insertMessage(message);
        conversation.appendMessage(message);

        L.e("from :" + Config.CUSTOM_SERVICE_IMID + " to :" + DemoHelper.getInstance().getCurrentUsernName());
        messageList.refresh();
    }

    /**
     * 设置属性，监听等
     */
    protected void setUpView() {
        titleBar.setTitle(toChatUsername);
        if (chatType == EaseConstant.CHATTYPE_SINGLE) { // 单聊
            // 设置标题
            if (EaseUserUtils.getUserInfo(toChatUsername) != null) {
                titleBar.setTitle(EaseUserUtils.getUserInfo(toChatUsername).getNick());
            }
            titleBar.setRightImageResource(R.drawable.ease_mm_title_remove);
        } else {
            titleBar.setRightImageResource(R.drawable.ease_to_group_details_normal);
            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                // 群聊
                EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
                if (group != null)
                    titleBar.setTitle(group.getGroupName());
                // 监听当前会话的群聊解散被T事件
           /*     groupListener = new GroupListener();
                EMClient.getInstance().groupManager().addGroupChangeListener(groupListener);*/
            } else {
                onChatRoomViewCreation();
            }

        }
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            onConversationInit();
            onMessageListInit();
        }

        // 设置标题栏点击事件
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        titleBar.setRightLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (chatType == EaseConstant.CHATTYPE_SINGLE) {
                    emptyHistory();
                } else {
                    toGroupDetails();
                }
            }
        });

        setRefreshLayoutListener();

        // show forward message if the message is not null
       /* String forward_msg_id = getArguments().getString("forward_msg_id");
        if (forward_msg_id != null) {
            // 发送要转发的消息
            forwardMessage(forward_msg_id);
        }*/
    }

    /**
     * 注册底部菜单扩展栏item; 覆盖此方法时如果不覆盖已有item，item的id需大于3
     */
    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length - 1; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], extendMenuItemClickListener);
        }
    }


    protected void onConversationInit() {
        // 获取当前conversation对象

        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
        // 把此会话的未读数置为0
        conversation.markAllMessagesAsRead();
        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
        }
    }

    protected void onMessageListInit() {
        messageList.init(toChatUsername, chatType, chatFragmentListener != null ?
                chatFragmentListener.onSetCustomChatRowProvider() : null);
        //设置list item里的控件的点击事件
        setListItemClickListener();

        messageList.getListView().setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                inputMenu.hideExtendMenuContainer();

                //用于聊天界面的顶上九宫格隐藏出现
                if (listTouch != null) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            // 触摸按下时的操作
                            listTouch.down();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            // 触摸移动时的操作

                            break;
                        case MotionEvent.ACTION_UP:
                            // 触摸抬起时的操作
                            listTouch.up();
                            break;
                    }
                }


                return false;
            }
        });

        isMessageListInited = true;
    }

    ListTouch listTouch;

    public void setListTouch(ListTouch listTouch) {
        this.listTouch = listTouch;
    }

    public interface ListTouch {
        void down();

        void up();
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {
                if (chatFragmentListener != null) {
                    chatFragmentListener.onAvatarClick(username);
                }
            }

            @Override
            public void onResendClick(final EMMessage message) {
//                new EaseAlertDialog(getActivity(), R.string.resend, R.string.confirm_resend, null, new AlertDialogUser() {
//                    @Override
//                    public void onResult(boolean confirmed, Bundle bundle) {
//                        if (!confirmed) {
//                            return;
//                        }
//                        resendMessage(message);
//                    }
//                }, true).show();


                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                builder.setTitle(R.string.resend);
                builder.setMessage(R.string.confirm_resend);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        resendMessage(message);
                    }
                });
                final AlertDialog alertDialog = builder.show();


                builder.setNegativeButton
                        ("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                alertDialog.dismiss();
                            }
                        });
            }

            @Override
            public void onBubbleLongClick(EMMessage message) {
                contextMenuMessage = message;
                if (chatFragmentListener != null) {
                    chatFragmentListener.onMessageBubbleLongClick(message);
                }
            }

            @Override
            public boolean onBubbleClick(EMMessage message) {
                if (chatFragmentListener != null) {
                    return chatFragmentListener.onMessageBubbleClick(message);
                }
                return false;
            }
        });
    }

    protected void setRefreshLayoutListener() {
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                if (cameraFile != null && cameraFile.exists())
                    sendImageMessage(cameraFile.getAbsolutePath());
            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        //   sendPicByUri(selectedImage);
                        Intent intent = new Intent(getContext(), EaseShowBigImageActivity.class);
                        intent.putExtra("uri", selectedImage);
                        intent.putExtra("type", "send");
                        startActivity(intent);
                    }
                }
            } else if (requestCode == REQUEST_CODE_MAP) { // 地图
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                String locationAddress = data.getStringExtra("address");
                if (locationAddress != null && !locationAddress.equals("")) {
                    sendLocationMessage(latitude, longitude, locationAddress);
                } else {
                    T.showShort(getActivity(), R.string.unable_to_get_loaction);

                }

            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (cameraFile != null)
            outState.putString("tempFile", cameraFile.getAbsolutePath());


        super.onSaveInstanceState(outState);

    }

    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {

            for (EMMessage message : messages) {
                String username = null;
                // 群组消息
                if (message.getChatType() == ChatType.GroupChat || message.getChatType() == ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    // 单聊消息
                    username = message.getFrom();
                }


                // 如果是当前会话的消息，刷新聊天页面

                if (username.equals(toChatUsername)) {

                    if (message.getType().equals(EMMessage.Type.TXT)) {
                        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                        String msg = txtBody.getMessage();

                        if (msg.contains("我去问问我的主人")) {
                            sendTextMessageToService("转人工");
                        } else if (msg.contains("正在转人工")) {
                            conversation.removeMessage(message.getMsgId());
                            //messageList.refreshSelectLast();
                        } else {
                            messageList.refreshSelectLast();
                        }
                    }
                    // 声音和震动提示有新消息
                    // EaseUI.getInstance().getNotifier().viberateAndPlayTone(message);
                    messageList.refreshSelectLast();
                    EaseUI.getInstance().getNotifier().viberateAndPlayTone(message);
                } else {
                    L.e("EaseChatFragment" + "消息不是和当前聊天ID的消息");
                    // 如果消息不是和当前聊天ID的消息
                    // EaseUI.getInstance().getNotifier().onNewMsg(message);
                }
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {

            if (isMessageListInited) {
                messageList.refresh();
            }
        }
    };


    public void setSudoku() {


    }

    @Override
    public void onResume() {
        super.onResume();


        boolean firstSend = (boolean) SPUtils.get(this.getContext(), Config.FIRST_SEND, true);
        String msg = "";
        if (firstSend) {
            if (WorkTimeUtil.isWork()) {
                msg += "感谢您的青睐。请问有什么可以为您效劳的?";
            } else {
                SPUtils.put(getActivity(), Config.IS_REMIND_SHOWED, true);
                msg += "感谢您的青睐。JO现在不在（工作时间是9:30-22:00），您可以在这里留言，JO会尽快联系您";
            }
            Boolean isRemindShowEd = (Boolean) SPUtils.get(getActivity(), Config.IS_REMIND_SHOWED, false);
            if (!isRemindShowEd) {
                EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
                message.setFrom(Config.CUSTOM_SERVICE_IMID);
                message.setTo(DemoHelper.getInstance().getCurrentUsernName());
                message.addBody(new EMTextMessageBody(msg));
                message.setChatType(EMMessage.ChatType.Chat);
                message.setTo(DemoHelper.getInstance().getCurrentUsernName());
                message.setMsgTime(System.currentTimeMillis());
                conversation.insertMessage(message);
                SPUtils.put(getActivity(), Config.IS_REMIND_SHOWED, true);
            }
            SPUtils.put(getActivity(), Config.FIRST_SEND, false);
        } else {

        }

        if (isMessageListInited)
            messageList.refresh();
        EaseUI.getInstance().pushActivity(getActivity());
        // register the event listener when enter the foreground
        EMClient.getInstance().chatManager().addMessageListener(msgListener);


        String messageId = DemoApplication.getInstance().getMessageId();
      /*  RealmList<XmppMessage> xmppMessages =
                RealmHelper.instance().findUser(toChatUsername).get(0).getXmppMessages();*/
        RealmResults<MessageRecordListBean> messageList = RealmHelper.instance().findMessageList("from");
        for (int i = 0; i < messageList.size(); i++) {
            if (messageList.get(i).equals(messageId)) {
                listView.smoothScrollToPosition(i);
                break;
            }
        }


    }


    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);

        // 把此activity 从foreground activity 列表里移除
        EaseUI.getInstance().popActivity(getActivity());


    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (groupListener != null) {
            EMClient.getInstance().groupManager().removeGroupChangeListener(groupListener);
        }
        if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
        }

        if (chatRoomChangeListener != null) {
            EMClient.getInstance().chatroomManager().removeChatRoomChangeListener(chatRoomChangeListener);
        }
    }

    public Boolean getInputMeanuIsShow() {
        return inputMenu.onBackPressed();
    }

    public void onBackPressed() {
        if (inputMenu.onBackPressed()) {
            getActivity().finish();
            //退出聊天室会导致不能收到消息

//            if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
//                EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
//            }
        }
    }

    protected void onChatRoomViewCreation() {
        final ProgressDialog pd = ProgressDialog.show(getActivity(), "", "Joining......");
        EMClient.getInstance().chatroomManager().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {

            @Override
            public void onSuccess(final EMChatRoom value) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity().isFinishing() || !toChatUsername.equals(value.getId()))
                            return;
                        pd.dismiss();
                        EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(toChatUsername);
                        if (room != null) {
                            titleBar.setTitle(room.getName());
                        } else {
                            titleBar.setTitle(toChatUsername);
                        }
                        EMLog.d(TAG, "join room success : " + room.getName());
                        addChatRoomChangeListenr();
                        onConversationInit();
                        onMessageListInit();
                    }
                });
            }

            @Override
            public void onError(final int error, String errorMsg) {
                // TODO Auto-generated method stub
                EMLog.d(TAG, "join room failure : " + error);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                    }
                });
                getActivity().finish();
            }
        });
    }


    protected void addChatRoomChangeListenr() {
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
    }


    /**
     * 扩展菜单栏item点击事件
     */
    class MyItemClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            if (chatFragmentListener != null) {
                if (chatFragmentListener.onExtendMenuItemClick(itemId, view)) {
                    return;
                }
            }
            switch (itemId) {


                case TIEM_EXPRESSION://表情
                    UMengUtils.click(getContext(), 4);
                    inputMenu.showEmoji();

                    break;
                case ITEM_TAKE_PICTURE: // 拍照
                    UMengUtils.click(getContext(), 5);
                    selectPicFromCamera();
                    break;
                case ITEM_PICTURE:
                    selectPicFromLocal(); // 图库选择图片
                    UMengUtils.click(getContext(), 6);
                    break;
                case ITEM_LOCATION: // 位置
                    //  startActivityForResult(new Intent(getActivity(), EaseBaiduMapActivity.class), REQUEST_CODE_MAP);
                    break;

                default:
                    break;
            }
        }

    }

    private ChatResultBean chatbean;

    //发送消息方法
    //==========================================================================
    protected void sendTextMessage(final String content) throws UnsupportedEncodingException {

        String s = Base64.encodeToString(content.getBytes("UTF-8"), Base64.DEFAULT);
        MessageRecordListBean messageRecordListBean = new MessageRecordListBean();
        messageRecordListBean.setType(1);
        messageRecordListBean.setContent(s);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        messageRecordListBean.setMessageDatetime(System.currentTimeMillis());
        messageRecordListBean.setMessageId(uuid);
        messageRecordListBean.setClientType(0);
        messageRecordListBean.setAccountId(user.getAccountId());
        messageRecordListBean.setMobile(user.getMobile());
        messageRecordListBean.setMessageFrom(serviceName);
        messageRecordListBean.setMessageTo(user.getImId());
        String s1 = new Gson().toJson(messageRecordListBean);
        messageRecordListBean.setContent(content);
        mySend(s1, user.getImId(), messageRecordListBean);
        // messageRecordListBean.
        //  sendLocalMessge(content);
    }

    public void mySend(String message, String to, final MessageRecordListBean xmppMessage) {
        SmackManager.getInstance().send(message, to, xmppMessage.getMessageId());
        Observable.just("").subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
               /* XmppUser xmppUser = RealmHelper.instance().findUser(toChatUsername).get(0);
                RealmHelper.instance().beginTran();
                RealmHelper.instance().insertNewMessage(xmppUser, xmppMessage);
                messageList.refresh();*/
                RealmHelper.instance().insertNewMessage(xmppMessage);
                messageList.refresh();
            }
        });
    }

    protected void sendBigExpressionMessage(String name, String identityCode) {
        EMMessage message = EaseCommonUtils.createExpressionMessage(toChatUsername, name, identityCode);
        sendMessage(message);

    }

    protected void sendVoiceMessage(String filePath, int length) {

        message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
        sendMessage(message);


    }

    protected void sendImageMessage(final String imagePath) {
        try {
            //   String s = Imageutils.bitmapToString(imagePath);
            final String uuid = UUID.randomUUID().toString().replaceAll("-", "");


            RequestHelper.getInstance().upPic(BitmapUtil.bitmapToFile(imagePath), uuid, new TextCallback() {
                @Override
                public void onFailure(String responseString) {

                }

                @Override
                public void onSuccess(Object responseString) {
                    try {
                        JSONObject jsonObject = new JSONObject((String) responseString);
                        if (jsonObject.getString("code").equals("2000")) {

                            MessageRecordListBean messageRecordListBean = new MessageRecordListBean();
                            messageRecordListBean.setType(3);
                            String data = jsonObject.getString("data");
                            String s = Base64.encodeToString(data.getBytes("UTF-8"), Base64.DEFAULT);
                            messageRecordListBean.setContent(s);
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                            messageRecordListBean.setMessageDatetime(System.currentTimeMillis());
                            messageRecordListBean.setMessageId(uuid);
                            messageRecordListBean.setClientType(0);
                            messageRecordListBean.setAccountId(user.getAccountId());
                            messageRecordListBean.setMobile(user.getMobile());
                            messageRecordListBean.setMessageFrom(serviceName);
                            messageRecordListBean.setMessageTo(user.getImId());
                            String s1 = new Gson().toJson(messageRecordListBean);
                            messageRecordListBean.setContent(imagePath);
                            mySend(s1, user.getImId(), messageRecordListBean);
                        } else {
                            T.showShort(getActivity(), jsonObject.getString("message"));
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }


        message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
        sendMessage(message);

    }

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        Log.e(TAG, "encodeBase64File: " + buffer.length);

        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        sendMessage(message);
    }

    protected void sendFileMessage(String filePath) {
        EMMessage message = EMMessage.createFileSendMessage(filePath, toChatUsername);
        sendMessage(message);
    }

    private String errorD;
    private String errorCode;

    protected void sendMessage(final EMMessage message) {
        if (message == null) {
            return;
        }
        if (chatFragmentListener != null) {
            //设置扩展属性
            chatFragmentListener.onSetMessageAttributes(message);
        }
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            message.setChatType(ChatType.GroupChat);
        } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            message.setChatType(ChatType.ChatRoom);
        }
        //发送消息


        EMClient.getInstance().chatManager().sendMessage(message);

        //刷新ui
        if (isMessageListInited) {
            messageList.refreshSelectLast();
        }
        message.setMessageStatusCallback(new EMCallBack() {


            @Override
            public void onSuccess() {
                Message obtain = Message.obtain();
                obtain.what = 0;
                handler.sendMessage(obtain);
                if (!WorkTimeUtil.isWork()) {
                    insertMessage(getString(R.string.welcome_no_work));
                }
            }

            @Override
            public void onError(int i, String s) {
                errorCode = i + "";
                errorD = s;

                Message obtain = Message.obtain();
                obtain.what = 1;
                handler.sendMessage(obtain);
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ChatResultBean chatResultBean = new ChatResultBean();
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    chatResultBean.setErrorCode(errorCode);
                    chatResultBean.setErrorDescription(errorD);
                    break;
            }
            chatResultBean.setConversationId(toChatUsername);
            chatResultBean.setSendTime(message.localTime() + "");
            chatResultBean.setSender(message.getFrom());

            chatResultBean.setReceiptTime(message.getMsgTime() + "");
            chatResultBean.setMessageId(message.getMsgId());
            chatResultBean.setStatus(message.status().name());

            if (message.getType().equals(EMMessage.Type.TXT)) {
                chatResultBean.setMessageType("1");
            } else if (message.getType().equals(EMMessage.Type.IMAGE)) {
                chatResultBean.setMessageType("2");
            } else if (message.getType().equals(EMMessage.Type.VIDEO)) {
                chatResultBean.setMessageType("3");
            } else if (message.getType().equals(EMMessage.Type.LOCATION)) {
                chatResultBean.setMessageType("4");
            } else if (message.getType().equals(EMMessage.Type.VOICE)) {
                chatResultBean.setMessageType("5");
            } else if (message.getType().equals(EMMessage.Type.FILE)) {
                chatResultBean.setMessageType("6");
            } else if (message.getType().equals(EMMessage.Type.CMD)) {
                chatResultBean.setMessageType("7");
            }
            if (message.status().equals(EMMessage.Status.CREATE)) {
                chatResultBean.setStatus("0");
            } else if (message.status().equals(EMMessage.Status.INPROGRESS)) {
                chatResultBean.setStatus("1");
            } else if (message.status().equals(EMMessage.Status.SUCCESS)) {
                chatResultBean.setStatus("2");
            } else if (message.status().equals(EMMessage.Status.FAIL)) {
                chatResultBean.setStatus("3");
            }

            super.handleMessage(msg);

        }
    };

    public void resendMessage(EMMessage message) {
        message.setStatus(EMMessage.Status.CREATE);
        EMClient.getInstance().chatManager().sendMessage(message);
        messageList.refresh();
    }

    //===================================================================================


    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    public void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            Log.e(TAG, "sendPicByUri: " + picturePath);
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImageMessage(file.getAbsolutePath());
        }

    }


    /**
     * 根据uri发送文件
     *
     * @param uri
     */
    protected void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            T.showShort(getActivity(), R.string.File_does_not_exist);
            return;
        }
        //大于10M不让发送
        if (file.length() > 10 * 1024 * 1024) {
            T.showShort(getActivity(), R.string.The_file_is_not_greater_than_10_m);
            return;
        }
        sendFileMessage(filePath);
    }

    /**
     * 照相获取图片
     */
    protected void selectPicFromCamera() {
        if (!EaseCommonUtils.isSdcardExist()) {
            T.showShort(getActivity(), R.string.sd_card_does_not_exist);
            return;
        }

        File skRoot = Environment.getExternalStorageDirectory();

        cameraFile = new File(skRoot.getAbsolutePath() + "/image/", System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        Log.e("camera", "save pic: " + cameraFile.getAbsolutePath());
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }


    /**
     * 从图库获取图片
     */
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }


    /**
     * 点击清空聊天记录
     */
    protected void emptyHistory() {
        String msg = getResources().getString(R.string.Whether_to_empty_all_chats);
        new EaseAlertDialog(getActivity(), null, msg, null, new AlertDialogUser() {

            @Override
            public void onResult(boolean confirmed, Bundle bundle) {
                if (confirmed) {
                    // 清空会话

                    EMClient.getInstance().chatManager().deleteConversation(toChatUsername, true);
                    messageList.refresh();
                }
            }
        }, true).show();
        ;
    }

    /**
     * 点击进入群组详情
     */
    protected void toGroupDetails() {
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                T.showShort(getActivity(), R.string.gorup_not_found);

                return;
            }
            if (chatFragmentListener != null) {
                chatFragmentListener.onEnterToChatDetails();
            }
        } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            if (chatFragmentListener != null) {
                chatFragmentListener.onEnterToChatDetails();
            }
        }
    }

    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    int startRow = 0;

    private void requestMessage() {


        RequestHelper.getInstance().recordList(getContext(), user.getAccountId(), startRow, 20, new TextCallback() {
            @Override
            public void onFailure(String responseString) {

            }

            @Override
            public void onSuccess(Object responseString) {
                RecordListBean bean = (RecordListBean) responseString;
                if (!bean.getCode().equals("2000")) {
                    T.showShort(getContext(), bean.getMessage());
                    return;
                }

                if (bean.getData() == null || bean.getData().getMessageRecordList() == null || bean.getData().getMessageRecordList().size() < 1) {
                    return;
                }
                List<MessageRecordListBean> messagedataList = bean.getData().getMessageRecordList();
                for (MessageRecordListBean messageRecordListBean : messagedataList) {
                    if (messageRecordListBean.getType() == 3) {
                        final byte[] decode = Base64.decode(messageRecordListBean.getContent(), Base64.DEFAULT);
                        String content = null;
                        try {
                            content = new String(decode, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        String picname = System.currentTimeMillis() + ".jpg";
                        final File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/image/" + picname);
                        file.getParentFile().mkdirs();
                        messageRecordListBean.setContent(file.getAbsolutePath());
                        RequestHelper.getInstance().downLoad(content, file, new TextCallback() {
                            @Override
                            public void onFailure(String responseString) {

                            }

                            @Override
                            public void onSuccess(Object responseString) {
                                //     ChatActivityNew.activityInstance.sendPic2Custome(file.getAbsoluteFile());
                            }
                        });
                    } else if (messageRecordListBean.getType() == 2) {
                        File skRoot = Environment.getExternalStorageDirectory();
                        String voiceFileName = getVoiceFileName("customer-service1");
                        String filePath = skRoot.getAbsolutePath() + "/voice/" + voiceFileName;
                        base642File(messageRecordListBean.getContent(), skRoot.getAbsolutePath() + "/voice/" + voiceFileName);
                        messageRecordListBean.setContent(filePath);

                    } else {
                        final byte[] decode = Base64.decode(messageRecordListBean.getContent(), Base64.DEFAULT);
                        String content = null;
                        try {
                            content = new String(decode, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        if (messageRecordListBean.getType() == 8) {
                            ChatCard chatCard = new ChatCard();
                            chatCard.setSubject("gif");
                            chatCard.setMessage(content);
                            Gson gson = new Gson();
                            String s1 = gson.toJson(chatCard);
                            messageRecordListBean.setContent(s1);
                        } else {
                            messageRecordListBean.setContent(content);
                        }

                    }
                    RealmHelper.instance().insertNewMessage(messageRecordListBean);
                }
                size = messagedataList.size();
                startRow = bean.getData().getStartRow();

            }
        });
    }

    private String getVoiceFileName(String uid) {
        Time now = new Time();
        now.setToNow();
        return uid + now.toString().substring(0, 15) + ".amr";
    }

    public EaseChatInputMenu getInputMenu() {
        return inputMenu;
    }

    public void base642File(String code, String path) {

        byte[] buffer = Base64.decode(code, Base64.DEFAULT);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected EaseChatFragmentListener chatFragmentListener;

    public void setChatFragmentListener(EaseChatFragmentListener chatFragmentListener) {
        this.chatFragmentListener = chatFragmentListener;
    }


    public interface EaseChatFragmentListener {
        /**
         * 设置消息扩展属性
         */
        void onSetMessageAttributes(EMMessage message);

        /**
         * 进入会话详情
         */
        void onEnterToChatDetails();

        /**
         * 用户头像点击事件
         *
         * @param username
         */
        void onAvatarClick(String username);

        /**
         * 消息气泡框点击事件
         */
        boolean onMessageBubbleClick(EMMessage message);

        /**
         * 消息气泡框长按事件
         */
        void onMessageBubbleLongClick(EMMessage message);

        /**
         * 扩展输入栏item点击事件,如果要覆盖EaseChatFragment已有的点击事件，return true
         *
         * @param view
         * @param itemId
         * @return
         */
        boolean onExtendMenuItemClick(int itemId, View view);

        /**
         * 设置自定义chatrow提供者
         *
         * @return
         */
        EaseCustomChatRowProvider onSetCustomChatRowProvider();
    }


}
